package com.niit

import org.apache.kafka.clients.producer.{KafkaProducer, ProducerConfig, ProducerRecord}
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.SparkConf
import org.apache.spark.sql.SQLContext
import org.apache.spark.streaming.kafka010.{ConsumerStrategies, KafkaUtils}
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.{Seconds, StreamingContext}

import java.util.{HashMap, Properties}

object Five {


  def main(args: Array[String]): Unit = {
    System.setProperty("hadoop.home.dir", "E:\\Hadoop\\hadoop-2.7.3")
    System.setProperty("HADOOP_USER_NAME", "root")
    val conf = new SparkConf().setMaster("local[*]").setAppName("kafkaDstream")
    val ssc = new StreamingContext(conf, Seconds(2))

    //导入sparksql依赖
    val sqlCon = new SQLContext(ssc.sparkContext)

    ssc.sparkContext.setLogLevel("error")
    val topic = "library"
    val group = "niit"
    val kafkaParams = Map[String, Object](
      // 1 kafka 所在地址
      "bootstrap.servers" -> "cheng:9092",

      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> group,

      // 消费模式 从头消费， 从尾消费，当前消费
      "auto.offset.reset" -> "earliest", //从头消费

      // 消费的元数据 信息， 消费的位置
      // 是否自动提交
      "enable.auto.commit" -> (false: java.lang.Boolean)
    )

    // 检查点目录
    ssc.checkpoint("./checkpoint")

    //连接kafka
    // 1. 创建直接流
    val linesStream = KafkaUtils.createDirectStream(
      ssc,
      //策略 PreferConsistent  kafka 集群 master /leader
      PreferConsistent,
      // 2. 订阅主题和参数
      ConsumerStrategies.Subscribe[String, String](Array(topic), kafkaParams)
    )
    // 提取value
    val line = linesStream.map(_.value())

    //line.print()
    // 对每一期的RDD进行操作
    line.foreachRDD(
      x => {

        val c1 = x.map(
          line => {
            val obg2 = line.split("\t")(0)
            val obg3 = line.split("\t")(2)
            val aa1 = obg3.toInt
            (obg2, aa1)
          }
        ).reduceByKey(_ + _)
        c1.foreach(
          x => {
            val type1 = x._1
            val num = x._2
            val str = type1 + "," + num
            println(str)
            // 发送kafka

            val kafkapro = new HashMap[String, Object]()
            //            kafkapro.put("bootstrap.servers", "cheng:9092")
            kafkapro.put("bootstrap.servers", "niit01:9092")
            kafkapro.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer")
            kafkapro.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer")

            val producer = new KafkaProducer[String, String](kafkapro)
            producer.send(new ProducerRecord[String, String]("library", res))
            producer.close()

          }
        )
      }
    )
        ssc.start()
        ssc.awaitTermination()
      }
  }



